<template>
  <div class="app-container">
    <div class="container">
      <!-- children:包含子节点字段，row-key：唯一标识 -->
      <div style="display: flex;float: right;margin: 5px 0 15px;">
        <el-button
          :disabled="label_save_btn"
          class="filter-item"
          size="mini"
          type="primary"
          @click="saveClick">保存
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="data"
        :tree-props="{ children: 'children' }"
        size="small"
        style="width: 100%;"
        row-key="variety_id">
        <!-- 下钻的一级目录 -->
        <el-table-column label="分类名称" >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.variety_name"
              clearable
              placeholder="请输入"
              style="width: 200px;"
              class="filter-item"
              size="small"
              @change="inputChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="移动" align="center">
          <template slot-scope="scope">
            <i class="el-icon-top" style="font-size: 25px;" @click="topClick(scope.row)"/>
            <i class="el-icon-bottom" style="font-size: 25px;" @click="bottomClick(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!--删除触发事件-->
            <el-popover
              :ref="scope.row.variety_id"
              placement="top"
              width="180">
              <p>确定删除本条数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="small" @click="$refs[scope.row.variety_id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="small" @click="subDelete(scope.row)">确定</el-button>
              </div>
              <!--删除按钮-->
              <el-button slot="reference" type="text" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!-- 图片放大预览功能 -->
      <imgMode ref="imgShow"/>
    </div>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import { mapGetters } from 'vuex'
import Cookies from 'js-cookie'
import imgMode from './imgMode'
import { delVariety, saveVariety } from '@/api/mall/commodityTypeRequest'
import slide from '../../commodity/label/slide'

/**
 * 注：
 * 1.要使用树形结构的表格，需要进行实体类拼装，且子节点名为children
 */
export default {
  components: { imgMode, slide },
  mixins: [initData],
  data() {
    return {
      // 附带参数， 公司id
      company_id: Cookies.get('company_id'),
      query: {},
      delLoading: false,
      curRowInfo: null,
      label_save_btn: false,
      varietyIdArray: []
    }
  },
  computed: {
    ...mapGetters([
      'userHeadUploadApi'
    ])
  },
  created() {
    this.$nextTick(() => {
      this.init().then(() => {
        // 插入空值
        this.recursionData()
      })
    })
  },
  methods: {
    recursionData() {
      this.data.map((item, i) => {
        // 最后一列添加一条空白数据
        if (i === (this.data.length - 1) && item.variety_name && item.variety_name.length > 0) {
          const info = {
            variety_id: this.uuid(),
            variety_name: '',
            icon_url: '',
            parent_id: '0',
            children: []
          }
          this.data.push(info)
        }
        this.addChildren(item)
      })
    },
    addChildren(item) {
      // 如果无二级分类，需要给一个默认空数组
      if (item.children === null) {
        item.children = []
      }
      // 原始对象集
      const info = {
        variety_id: this.uuid(),
        variety_name: '',
        icon_url: '',
        parent_id: item.variety_id
      }
      // 对象存在，为该对象添加一条空数据
      if (item['children'] && item['children'].length > 0) {
        const list = item['children']
        list.map((item, i) => {
          if (i === (list.length - 1) && item.variety_name && item.variety_name.length > 0) {
            list.push(info)
          }
        })
      } else {
        // 对象不存在则赋值一个数组，数组包含一条空数据
        item['children'].push(info)
      }
    },
    beforeInit() {
      this.url = 'api/commodity-variety'
      const sort = 'sort'
      this.params = { page: this.page, size: this.size, sort: sort }
      return true
    },
    uuid() {
      const s = []
      const hexDigits = '0123456789abcdef'
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4'
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
      s[8] = s[13] = s[18] = s[23] = '-'
      return s.join('')
    },
    viewImg(url) {
      // 图片放大预览
      this.$refs.imgShow.dialog = true
      this.$refs.imgShow.imgUrl = url
    },
    delImg(info) {
      // 删除图片
      info.icon_url = ''
    },
    inputChange() {
      // input输入后自动添加一条新的空白行
      this.recursionData()
    },
    topClick(row) {
      // 向上移动事件
      if (row.parent_id === '0') {
        const index = this.getIndex(row, this.data)
        // 一级目录移动、
        if (index !== 0) {
          this.data[index] = this.data.splice(index - 1, 1, this.data[index])[0]
        } else {
          this.$message({
            message: '已经是最顶端了，不能再移动了。。。',
            type: 'warning'
          })
        }
      } else {
        // 二级目录移动
        this.data.map((item) => {
          if (item.variety_id === row.parent_id) {
            const index = this.getIndex(row, item.children)
            if (index !== 0) {
              item.children[index] = item.children.splice(index - 1, 1, item.children[index])[0]
            } else {
              this.$message({
                message: '已经是当前结构的最顶端了，不能再移动了。。。',
                type: 'warning'
              })
            }
          }
        })
      }
    },
    getIndex(info, list) {
      let num = 0
      // 获取当前list的位置
      list.map((item, i) => {
        if (item.variety_id === info.variety_id) {
          num = i
        }
      })
      return num
    },
    bottomClick(row) {
      // 向下移动事件
      if (row.parent_id === '0') {
        const index = this.getIndex(row, this.data)
        // 一级目录移动、
        if (index !== this.data.length - 1) {
          this.data[index] = this.data.splice(index + 1, 1, this.data[index])[0]
        } else {
          this.$message({
            message: '已经是最低端了，不能再移动了。。。',
            type: 'warning'
          })
        }
      } else {
        // 二级目录移动
        this.data.map((item) => {
          if (item.variety_id === row.parent_id) {
            const index = this.getIndex(row, item.children)
            if (index !== item.children.length - 1) {
              item.children[index] = item.children.splice(index + 1, 1, item.children[index])[0]
            } else {
              this.$message({
                message: '已经是当前结构的最低端了，不能再移动了。。。',
                type: 'warning'
              })
            }
          }
        })
      }
    },
    saveClick() {
      this.label_save_btn = true
      const param = { varietyData: JSON.stringify(this.data), varietyIds: this.varietyIdArray }
      saveVariety(param).then(res => {
        if (res.result) {
          this.init().then(() => {
            this.recursionData()
          })
          this.$notify({
            title: res.msg,
            type: 'success',
            duration: 2500
          })
        } else {
          this.$notify({
            title: res.msg,
            type: 'error',
            duration: 2500
          })
        }
        this.label_save_btn = false
      })
    },
    subDelete(row) {
      this.delLoading = true
      if (row.parent_id === '0') {
        // 删除一级分类
        const param = { variety_id: row.variety_id }
        delVariety(param).then(res => {
          if (res.result) {
            const index = this.getIndex(row, this.data)
            // 将当前行删除的一级分类id存到数组，点击保存时传递到后台进行逻辑删除
            this.varietyIdArray.push(row.variety_id)
            this.data.splice(index, 1)
          } else {
            this.$notify({
              title: res.msg,
              type: 'error',
              duration: 2500
            })
          }
        })
      } else {
        // 删除二级分类
        this.data.map((item) => {
          if (item.variety_id === row.parent_id) {
            const param = { second_variety_id: row.variety_id }
            delVariety(param).then(res => {
              if (res.result) {
                const index = this.getIndex(row, item.children)
                item.children.splice(index, 1)
              } else {
                this.$notify({
                  title: res.msg,
                  type: 'error',
                  duration: 2500
                })
              }
            })
          }
        })
      }
      this.delLoading = false
      this.$refs[row.variety_id].doClose()
    },
    resetQuery() {
      this.$refs['query'].resetFields()
    },
    userImgSuccess(res) {
      // 数据回显至原表格，由于在点击之前已经把表格中该行的数据存于this.curRowInfo字段中，相当于把引用给了该字段
      // 所以改变this.curRowInfo中的值也就改变了表格中的值
      this.curRowInfo.icon_url = res
    },
    beforeUserImgUpload(file) {
      const isJPG = file.type === 'image/jpeg' ? true : file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    selectCarouse(row) {
      this.curRowInfo = row
      this.$refs.slide.sliderDialog = true
    },
    setCarouse(carouse) {
      if (carouse && carouse.carouse_id) {
        this.$set(this.curRowInfo, 'carouse_img', carouse.image_url)
        this.$set(this.curRowInfo, 'carouse_id', carouse.carouse_id)
        this.$refs.slide.sliderDialog = false
      } else {
        this.$message({
          message: '请选择轮播图！',
          type: 'warning'
        })
      }
    },
    delCarouseImg(info) {
      // 删除轮播图图片
      info.carouse_img = ''
      info.carouse_id = ''
    }
  }
}
</script>

<style scoped>

</style>

